package cn.tedu.luban.demo.gateway.filters;

import cn.tedu.luban.demo.gateway.GatewayMain;
import cn.tedu.luban.demo.gateway.ex.GatewayException;
import com.alibaba.nacos.common.utils.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
public class AuthenticationFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1 取数据
        try{
            String token=gainToken(exchange);
            //2.其它token的解析 TODO 从redis读user数据
            //流程继续 认证成功
            return chain.filter(exchange);
        }catch (GatewayException e){
            e.printStackTrace();
            return Mono.error(e);
            //输出响应??
        }
    }

    private String gainToken(ServerWebExchange exchange) throws RuntimeException{
        //1. 拿到请求
        ServerHttpRequest request = exchange.getRequest();
        String token=null;
        //2. queryParam传递?token=123213213
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        List<String> queryToken = queryParams.get("token");
        if (CollectionUtils.isNotEmpty(queryToken)){
            token=queryParams.get("token").get(0);
        }
        //3. header cookie
        if (token==null){
            List<String> authorization = request.getHeaders().get("Authorization");
            if (CollectionUtils.isNotEmpty(authorization)){
                token=authorization.get(0);
            }
        }
        if (token==null){
            List<HttpCookie> cookieToken = request.getCookies().get("token");
            if (CollectionUtils.isNotEmpty(cookieToken)){
                token=cookieToken.get(0).getValue();
            }
        }
        if (token==null){
            //当前请求没有携带token
            throw new GatewayException("token没有携带票据");
        }
        //验证一下正则
        boolean matches = token.matches("\\d{10}");
        if (!matches){
            //token有值 但是不满足10数字的格式
            throw new GatewayException("你的token格式不正确");
        }
        return token;
    }

    @Override
    public int getOrder() {
        return 0;
    }


}
